#include "tcpTransport.h"

namespace OmronPlc {
	tcpTransport::tcpTransport() {
	}

	tcpTransport::~tcpTransport() {
	}

	void tcpTransport::SetRemote(cstr_t ip, uint16_t port) {
		_ip = ip;
		_port = port;
	}

	bool tcpTransport::Connect() {
		_socket.Connect(_ip, _port);
		return false;
	}
	bool tcpTransport::IsConnectd() {
		return  _socket.IsConnect();
	}

	void tcpTransport::Close() {
		_socket.close();
	}

	int tcpTransport::Send(const uint8_t command[], int cmdLen) {
		if (!IsConnectd()) {
			return 0;
		}
		for (int i = 0; i < cmdLen; i++) {
			if (i mod 32 == 0) {
				osPrintf("\nsend->");
			}
			else if (i mod 4 == 0) {
				osPrintf(" ");
			}		
			osPrintf("%'02X", command[i]);	
		}
		int bytesSent = _socket.write(command, cmdLen);

		return bytesSent;
	}

	int tcpTransport::Receive(uint8_t response[], int respLen) {
		if (!IsConnectd()) {
			return 0;
		}

		int bytesRecv =  _socket.read(response, respLen);

		for (int i = 0; i < bytesRecv; i++) {
			if (i mod 32 == 0) {
				osPrintf("\nrecv<-");
			}
			else if (i mod 4 == 0) {
				osPrintf(" ");
			}
			osPrintf("%'02X", response[i]);
		}

		return bytesRecv;
	}
}
